package com.project.util;

import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WechatToXml {

    /**
     * 此方法将输入流中的数据封装入map
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String,String> xmlToMap(HttpServletRequest request)throws  Exception{
        Map<String,String> map = new HashMap<String, String>();
        /**
         *  把request 中的数据转换成map格式
         */
        SAXReader saxReader = new SAXReader();
        //获得流
        /*InputStream is = request.getInputStream();*/
        //封装成为xml
        Document doc = saxReader.read(request.getReader());
        Element root = doc.getRootElement();
        List<Element> lists = root.elements();

        //放入map
        for (Element el: lists) {
            map.put(el.getName(),el.getText());
        }
        //关闭流

        return map;
    }


    public static  String textMsgToXml(TextMessage textMessage){
        XStream xStream = new XStream();
        xStream.alias("xml",textMessage.getClass());
        return xStream.toXML(textMessage);
    }

    public static String textMsg(String toUserName,String fromUserName,String content){
        TextMessage text = new TextMessage();
        text.setFromUserName(toUserName);
        text.setToUserName(fromUserName);
        text.setMsgType("text");
        text.setCreateTime(new Date().getTime());
        text.setContent(content);
        return textMsgToXml(text);
    }

}
